package com.administrator.cloudapplication.tools;

import android.content.Context;
import android.os.Build;
import android.os.Handler;
import android.util.Log;

import com.administrator.cloudapplication.callback.ReqCallBack;
import com.administrator.cloudapplication.constant.Urls;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * package: com.ftgj.luoyangculture.tools.HttpUtils
 * author: gyc
 * description:简单封装Okhttp
 * time: create at 2017/4/11 22:00
 */

public class HttpUtils {

    private volatile static HttpUtils mInstance;
    public static OkHttpClient mOkHttpClient;

    public static final int TYPE_GET = 0;//get请求
    public static final int TYPE_POST_JSON = 1;//post请求参数为json
    public static final int TYPE_POST_FORM = 2;//post请求参数为表单
    private static final String TAG = HttpUtils.class.getSimpleName();
    private Handler okHttpHandler;//全局处理子线程和M主线程通信

    //mdiatype 这个需要和服务端保持一致
    private static final MediaType MEDIA_TYPE_JSON = MediaType.parse
            ("application/x-www-form-urlencoded; charset=utf-8");

    private HttpUtils(OkHttpClient okHttpClient, Context context) {
        if (okHttpClient == null) {
            mOkHttpClient = new OkHttpClient();
        } else {
            mOkHttpClient = okHttpClient;
        }
        //初始化Handler
        okHttpHandler = new Handler(context.getMainLooper());
    }

    /**
     * 初始化HttpUtils
     *
     * @param okHttpClient
     * @param context
     * @return
     */
    public static HttpUtils initClient(OkHttpClient okHttpClient, Context context) {
        if (mInstance == null) {
            synchronized (HttpUtils.class) {
                if (mInstance == null) {
                    mInstance = new HttpUtils(okHttpClient, context);
                }
            }
        }
        return mInstance;
    }

    /**
     * 获取HttpUtils实例
     *
     * @param context
     * @return
     */
    public static HttpUtils getInstance(Context context) {
        return initClient(null, context);
    }

    /**
     * okHttp异步请求统一入口
     *
     * @param url         接口地址
     * @param requestType 请求类型
     * @param paramsMap   请求参数
     * @param callBack    请求返回数据回调
     **/
    public Call requestAsyn(String url, int requestType, HashMap<String, String> paramsMap,
                            ReqCallBack callBack,int flag) {
        Call call = null;
        switch (requestType) {
            case TYPE_GET:
                call = requestGetByAsyn(url, paramsMap, callBack,flag);
                break;
            case TYPE_POST_JSON:
                call = requestPostByAsyn(url, paramsMap, callBack,flag);
                break;
            case TYPE_POST_FORM:
                call = requestPostByAsynWithForm(url, paramsMap, callBack,flag);
                break;
        }
        return call;
    }


    private Call requestGetByAsyn(String actionUrl, HashMap<String, String> paramsMap, final
    ReqCallBack callBack,final int flag) {
        StringBuilder tempParams = new StringBuilder();
        try {
            int pos = 0;
            if (paramsMap != null) {
                for (String key : paramsMap.keySet()) {
                    if (pos > 0) {
                        tempParams.append("&");
                    }
                    tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get
                            (key), "utf-8")));
                    pos++;
                }
            }

            String requestUrl = String.format("%s%s?%s", Urls.BASE_URL, actionUrl, tempParams
                    .toString());
            final Request request = addHeaders().url(requestUrl).build();
            final Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    failedCallBack("访问失败", callBack,flag);
                    Log.e(TAG, e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.e(TAG, "response ----->" + string);
                        successCallBack(string, callBack,flag);
                    } else {
                        failedCallBack("服务器错误", callBack,flag);
                    }
                }
            });
            return call;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return null;
    }
    public Call requestGet(String baseUrl,String actionUrl, HashMap<String, String> paramsMap, final
    ReqCallBack callBack,final int flag) {
        StringBuilder tempParams = new StringBuilder();
        try {
            int pos = 0;
            if (paramsMap != null) {
                for (String key : paramsMap.keySet()) {
                    if (pos > 0) {
                        tempParams.append("&");
                    }
                    tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get
                            (key), "utf-8")));
                    pos++;
                }
            }

            String requestUrl = String.format("%s%s?%s", baseUrl, actionUrl, tempParams
                    .toString());
            final Request request = addHeaders().url(requestUrl).build();
            final Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    failedCallBack("访问失败", callBack,flag);
                    Log.e(TAG, e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.e(TAG, "response ----->" + string);
                        successCallBack(string, callBack,flag);
                    } else {
                        failedCallBack("服务器错误", callBack,flag);
                    }
                }
            });
            return call;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return null;
    }
    /**
     * okHttp post异步请求
     *
     * @param actionUrl 接口地址
     * @param paramsMap 请求参数
     * @param callBack  请求返回数据回调
     * @return
     */
    public Call requestPostByAsyn(String actionUrl, HashMap<String, String> paramsMap, final
    ReqCallBack callBack, final int flag) {
        try {
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            if (paramsMap != null) {
                for (String key : paramsMap.keySet()) {
                    if (pos > 0) {
                        tempParams.append("&");
                    }
                    tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get
                            (key), "utf-8")));
                    pos++;
                }
            }

            String params = tempParams.toString();
            RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, params);
            String requestUrl = String.format("%s%s", Urls.BASE_URL, actionUrl);
            final Request request = addHeaders().url(requestUrl).post(body).build();
            final Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    failedCallBack("访问失败", callBack,flag);
                    Log.e(TAG, e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.e(TAG, "response ----->" + string);
                        successCallBack(string, callBack,flag);
                    } else {
                        failedCallBack("服务器错误",callBack,flag);
                    }
                }
            });
            return call;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return null;
    }

    /**
     * okHttp post异步请求
     *
     * @param actionUrl 接口地址
     * @param paramsMap 请求参数
     * @param callBack  请求返回数据回调
     * @return
     */
    public Call requestPostByAsyn2(String actionUrl, HashMap<String, String> paramsMap, final
    ReqCallBack callBack,final  int flag) {
        try {
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            if (paramsMap != null) {
                for (String key : paramsMap.keySet()) {
                    if (pos > 0) {
                        tempParams.append("&");
                    }
                    tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get
                            (key), "utf-8")));
                    pos++;
                }
            }

            String params = tempParams.toString();
            RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, params);
            String requestUrl = String.format("%s%s", Urls.BASE_URL2, actionUrl);
            final Request request = addHeaders().url(requestUrl).post(body).build();
            final Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    failedCallBack("访问失败", callBack,flag);
                    Log.e(TAG, e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.e(TAG, "response ----->" + string);
                        successCallBack(string, callBack,flag);
                    } else {
                        failedCallBack("服务器错误",callBack,flag);
                    }
                }
            });
            return call;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return null;
    }

    /**
     * 统一为请求添加头信息
     *
     * @return
     */
    public static Request.Builder addHeaders() {
        Request.Builder builder = new Request.Builder()
                .addHeader("Connection", "keep-alive")
                .addHeader("platform", "2")
                .addHeader("phoneModel", Build.MODEL)
                .addHeader("systemVersion", Build.VERSION.RELEASE);
        return builder;
    }

    /**
     * 统一同意处理成功信息
     *
     * @param result
     * @param callBack
     */
    private void successCallBack(final String result, final ReqCallBack callBack,final int flag) {
        okHttpHandler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    //可在此处更新UI
                    callBack.onReqSuccess(result,flag);
                }
            }
        });
    }

    /**
     * 统一处理失败信息
     *
     * @param errorMsg
     * @param callBack
     */
    private void failedCallBack(final String errorMsg, final ReqCallBack callBack,final int flag) {
        okHttpHandler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null) {
                    //可在此处更新UI
                    callBack.onReqFailed(errorMsg,flag);
                }
            }
        });
    }


    /**
     * okHttp post异步请求表单提交
     *
     * @param actionUrl 接口地址
     * @param paramsMap 请求参数
     * @param callBack  请求返回数据回调
     * @return
     */
    private Call requestPostByAsynWithForm(String actionUrl, HashMap<String, String> paramsMap,
                                           final ReqCallBack callBack,final int flag) {
        try {
            FormBody.Builder builder = new FormBody.Builder();
            for (String key : paramsMap.keySet()) {
                builder.add(key, paramsMap.get(key));
            }
            RequestBody formBody = builder.build();
            String requestUrl = String.format("%s%s", Urls.BASE_URL, actionUrl);
            final Request request = addHeaders().url(requestUrl).post(formBody).build();
            final Call call = mOkHttpClient.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    failedCallBack("访问失败", callBack,flag);
                    Log.e(TAG, e.toString());
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Log.e(TAG, "response ----->" + string);
                        successCallBack(string, callBack,flag);
                    } else {
                        failedCallBack("服务器错误", callBack,flag);
                    }
                }
            });
            return call;
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return null;
    }


    /**
     * okHttp同步请求统一入口
     *
     * @param actionUrl   接口地址
     * @param requestType 请求类型
     * @param paramsMap   请求参数
     */
    public String requestSyn(String actionUrl, int requestType, HashMap<String, String> paramsMap) {
        switch (requestType) {
            case TYPE_GET:
                return requestGetBySyn(actionUrl, paramsMap);
            case TYPE_POST_JSON:
                return requestPostBySyn(actionUrl, paramsMap);
            case TYPE_POST_FORM:
                return requestPostBySynWithForm(actionUrl, paramsMap);
        }
        return null;
    }

    /**
     * okHttp get同步请求
     *
     * @param actionUrl 接口地址
     * @param paramsMap 请求参数
     */
    private String requestGetBySyn(String actionUrl, HashMap<String, String> paramsMap) {
        StringBuilder tempParams = new StringBuilder();
        try {
            //处理参数
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                //对参数进行URLEncoder
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get
                        (key), "utf-8")));
                pos++;
            }
            //补全请求地址
            String requestUrl = String.format("%s%s?%s", Urls.BASE_URL, actionUrl, tempParams
                    .toString());
            //创建一个请求
            Request request = addHeaders().url(requestUrl).build();
            //创建一个Call
            final Call call = mOkHttpClient.newCall(request);
            //执行请求
            final Response response = call.execute();
            return response.body().string();
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return null;
    }

    /**
     * okHttp post同步请求
     *
     * @param actionUrl 接口地址
     * @param paramsMap 请求参数
     */
    private String requestPostBySyn(String actionUrl, HashMap<String, String> paramsMap) {
        try {
            //处理参数
            StringBuilder tempParams = new StringBuilder();
            int pos = 0;
            for (String key : paramsMap.keySet()) {
                if (pos > 0) {
                    tempParams.append("&");
                }
                tempParams.append(String.format("%s=%s", key, URLEncoder.encode(paramsMap.get
                        (key), "utf-8")));
                pos++;
            }
            //补全请求地址
            String requestUrl = String.format("%s%s", Urls.BASE_URL, actionUrl);
            //生成参数
            String params = tempParams.toString();
            //创建一个请求实体对象 RequestBody
            RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, params);
            //创建一个请求
            final Request request = addHeaders().url(requestUrl).post(body).build();
            //创建一个Call
            final Call call = mOkHttpClient.newCall(request);
            //执行请求
            Response response = call.execute();
            //请求执行成功
            if (response.isSuccessful()) {
                //获取返回数据 可以是String，bytes ,byteStream
                Log.e(TAG, "response ----->" + response.body().string());
                return response.body().string();
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return null;
    }

    /**
     * okHttp post同步请求表单提交
     *
     * @param actionUrl 接口地址
     * @param paramsMap 请求参数
     */
    private String requestPostBySynWithForm(String actionUrl, HashMap<String, String> paramsMap) {
        try {
            //创建一个FormBody.Builder
            FormBody.Builder builder = new FormBody.Builder();
            for (String key : paramsMap.keySet()) {
                //追加表单信息
                builder.add(key, paramsMap.get(key));
            }
            //生成表单实体对象
            RequestBody formBody = builder.build();
            //补全请求地址
            String requestUrl = String.format("%s%s", Urls.BASE_URL, actionUrl);
            //创建一个请求
            final Request request = addHeaders().url(requestUrl).post(formBody).build();
            //创建一个Call
            final Call call = mOkHttpClient.newCall(request);
            //执行请求
            Response response = call.execute();
            if (response.isSuccessful()) {
                Log.e(TAG, "response ----->" + response.body().string());
                return response.body().string();
            }
        } catch (Exception e) {
            Log.e(TAG, e.toString());
        }
        return null;
    }
}
